package Hbase;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;

/**
 * @author: yehw
 * @date: 2020/9/3 21:06
 * @description: 协处理器
 */
public class MyObserver  extends BaseRegionObserver {
    /**
    * @author:yehw
    * @date: 2020/9/3:21:09
    * @paramType:
    * @returnType:
    * @description:  删除操作
    */
    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        //获得表
        HTableInterface friend = e.getEnvironment().getTable(TableName.valueOf("friend"));
        //获得删除行的数据
        byte[] row = delete.getRow();
        //获得所有cell对象
        NavigableMap<byte[], List<Cell>> familyCellMap = delete.getFamilyCellMap();

        Set<Map.Entry<byte[], List<Cell>>> entries = familyCellMap.entrySet();

        for (Map.Entry<byte[], List<Cell>> entry : entries) {
            //获得单元
            List<Cell> value = entry.getValue();
            for (Cell cell : value) {
                //获得rowkey信息
                byte[] bytes = CellUtil.cloneRow(cell);
                //获得列信息
                byte[] bytes1 = CellUtil.cloneQualifier(cell);
                Get friends = new Get(bytes1).addColumn(Bytes.toBytes("friends"),bytes);
                boolean exists = friend.exists(friends);
                if (exists) {
                    Delete friends1 = new Delete(bytes1).addColumn(Bytes.toBytes("friends"), row);
                    friend.delete(friends1);

                }
            }
        }

    };

}
